import { PageContainer } from '@ant-design/pro-components';
import { useDispatch, useNavigate, useSelector } from '@umijs/max';
import { message } from 'antd';
import { useEffect, useState } from 'react';
import AdminForm from './components/adminForm';
const AddAdmin = () => {
  const [adminInfo, setAdminInfo] = useState({
    loginId: '',
    loginPwd: '',
    nickname: '',
    permission: 2,
    avatar: '',
  });
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { adminList } = useSelector((state) => state.admin);

  useEffect(() => {
    if (!adminList.length) {
      dispatch({
        type: 'admin/_initAdminList',
      });
    }
  }, [adminList]);

  const [messageApi, contextHolder] = message.useMessage();

  const setNewAdminInfo = (newVal) => {
    setAdminInfo(newVal);
  };
  const submitHandle = () => {
    dispatch({
      type: 'admin/_addAdmin',
      payload: adminInfo,
    });
    messageApi.open({
      type: 'success',
      content: '新增管理员成功！',
    });
    setTimeout(() => {
      navigate('/admin/adminList');
    }, 2000);
  };

  return (
    <div>
      <PageContainer>
        <div className="container" style={{ width: '500px' }}>
          <AdminForm
            type="add"
            adminInfo={adminInfo}
            setAdminInfo={setNewAdminInfo}
            submitHandle={submitHandle}
          />
        </div>
      </PageContainer>
      {contextHolder}
    </div>
  );
};

export default AddAdmin;
